const http = require('http');
const net = require('net');

function checkPort(port) {
  return new Promise((resolve) => {
    const server = net.createServer();
    
    server.listen(port, () => {
      server.once('close', () => {
        resolve(true); // 端口可用
      });
      server.close();
    });
    
    server.on('error', () => {
      resolve(false); // 端口被占用
    });
  });
}

function checkHttpService(url) {
  return new Promise((resolve) => {
    const options = {
      method: 'GET',
      timeout: 3000
    };
    
    const req = http.request(url, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        resolve({
          status: res.statusCode,
          success: res.statusCode === 200,
          data: data
        });
      });
    });
    
    req.on('error', () => {
      resolve({
        status: 0,
        success: false,
        data: null
      });
    });
    
    req.on('timeout', () => {
      req.destroy();
      resolve({
        status: 0,
        success: false,
        data: null
      });
    });
    
    req.end();
  });
}

async function runDiagnosis() {
  console.log('🔍 UC系统诊断开始...\n');
  
  // 检查端口状态
  console.log('📡 端口状态检查:');
  const ports = [4000, 5001, 8102];
  for (const port of ports) {
    const isAvailable = await checkPort(port);
    console.log(`  端口 ${port}: ${isAvailable ? '✅ 可用' : '❌ 被占用'}`);
  }
  
  console.log('\n🌐 HTTP服务检查:');
  
  // 检查后端服务
  try {
    const backendCheck = await checkHttpService('http://localhost:4000/api/health');
    if (backendCheck.success) {
      console.log('  后端服务 (4000): ✅ 正常');
    } else {
      console.log('  后端服务 (4000): ❌ 异常');
    }
  } catch (error) {
    console.log('  后端服务 (4000): ❌ 连接失败');
  }
  
  // 检查AI服务
  try {
    const aiCheck = await checkHttpService('http://localhost:5001/health');
    if (aiCheck.success) {
      console.log('  AI服务 (5001): ✅ 正常');
    } else {
      console.log('  AI服务 (5001): ❌ 异常');
    }
  } catch (error) {
    console.log('  AI服务 (5001): ❌ 连接失败');
  }
  
  // 检查前端服务
  try {
    const frontendCheck = await checkHttpService('http://localhost:8102');
    if (frontendCheck.success) {
      console.log('  前端服务 (8102): ✅ 正常');
    } else {
      console.log('  前端服务 (8102): ❌ 异常');
    }
  } catch (error) {
    console.log('  前端服务 (8102): ❌ 连接失败');
  }
  
  console.log('\n📋 建议操作:');
  console.log('1. 如果端口被占用，请运行 complete_system_restart.bat');
  console.log('2. 如果服务异常，请检查对应的日志文件');
  console.log('3. 如果问题持续，请重启计算机后重试');
  
  console.log('\n🎯 访问地址:');
  console.log('- 前端界面: http://localhost:8102');
  console.log('- 后端API: http://localhost:4000/api/health');
  console.log('- AI服务: http://localhost:5001/health');
}

runDiagnosis().catch(console.error);
